package com.zhht.htzx.ui;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.kunminx.binding_recyclerview.adapter.SimpleDataBindingAdapter;
import com.nsgf.library.data.bean.UserDataBean;
import com.nsgf.library.data.bean.UserDataBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhht.htzx.BR;
import com.zhht.htzx.R;
import com.zhht.htzx.databinding.ActivityUserRecordBinding;
import com.zhht.htzx.databinding.ActivityVirtualCurrencyBinding;
import com.zhht.htzx.databinding.ItemBusinessUserRecordBinding;
import com.zhht.htzx.databinding.ItemMinePointsRedBinding;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户管理
 */
public class UserRecordActivity extends BaseActivity {

    private UserRecordStateHolder mStates;

    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(UserRecordStateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    private SimpleDataBindingAdapter<UserDataBean.ListBean, ItemBusinessUserRecordBinding> mAdapter;

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new SimpleDataBindingAdapter<UserDataBean.ListBean, ItemBusinessUserRecordBinding>(this, R.layout.item_business_user_record,
                new DiffUtil.ItemCallback<UserDataBean.ListBean>() {
                    @Override
                    public boolean areItemsTheSame(@NonNull UserDataBean.ListBean oldItem, @NonNull UserDataBean.ListBean newItem) {
                        return oldItem.getIdX() == newItem.getIdX();
                    }

                    @Override
                    public boolean areContentsTheSame(@NonNull UserDataBean.ListBean oldItem, @NonNull UserDataBean.ListBean newItem) {

                        if (oldItem.getIdX() != newItem.getIdX())
                            return false;
                        if (!oldItem.getMobileX().equals(newItem.getMobileX()))
                            return false;
                        if (!oldItem.getNicknameX().equals(newItem.getNicknameX()))
                            return false;
                        if (!oldItem.getRankName().equals(newItem.getRankName()))
                            return false;
                        if (oldItem.getPointX() != newItem.getPointX())
                            return false;

                        return true;
                    }
                }) {
            @Override
            protected void onBindItem(ItemBusinessUserRecordBinding binding, UserDataBean.ListBean item,
                                      RecyclerView.ViewHolder holder) {
                binding.setVm(item);

            }
        };
        return new DataBindingConfig(R.layout.activity_user_record, BR.vm, mStates)
                .addBindingParam(BR.adapter, mAdapter);
    }

    private ActivityUserRecordBinding mBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mBinding = (ActivityUserRecordBinding) getBinding();
        mStates.titleBar.set("用户管理");

        mBinding.swipeRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getUserRecord();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getUserRecord();
            }
        });


        mAccountRequester.getUserDataResult().observe(this, new Observer<ResponseStatus<UserDataBean>>() {
            @Override
            public void onChanged(ResponseStatus<UserDataBean> response) {
                if (response.getResponseCode() == 0) {

                    if (page == 1) {
                        mBinding.swipeRefreshLayout.finishRefresh();
                        mStates.userRecordList.set(response.getData().getList());
                        if (!mStates.userRecordList.get().isEmpty())
                            mBinding.ivListNotData.setVisibility(GONE);
                        else mBinding.ivListNotData.setVisibility(VISIBLE);
                    } else {
                        mBinding.swipeRefreshLayout.finishLoadMore();

                        List<UserDataBean.ListBean> currentList = mStates.userRecordList.get();
                        if (currentList != null) {
                            currentList.addAll(response.getData().getList());
                            mStates.userRecordList.set(currentList);
                        }
                    }
                }
            }
        });

        mBinding.swipeRefreshLayout.autoRefresh();

        mAdapter.setOnItemClickListener(new BaseDataBindingAdapter.OnItemClickListener<UserDataBean.ListBean>() {
            @Override
            public void onItemClick(int viewId, UserDataBean.ListBean item, int position) {
                startActivity(new Intent()
                        .putExtra("data", item)
                        .setClass(UserRecordActivity.this, UserRecordSettingActivity.class));
            }
        });


        mBinding.etSearchUser.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    keywords = v.getText().toString();
                    page = 1;
                    // 在这里执行搜索操作
                    mBinding.swipeRefreshLayout.autoRefresh();
                    return true; // 消费事件，防止默认行为
                }
                return false; // 不消费事件，允许默认行为
            }
        });


    }

    private int page = 1;

    private String keywords;

    private void getUserRecord() {
        mAccountRequester.getUserRecord(page, keywords);
    }

    public static class UserRecordStateHolder extends StateHolder {

        public final State<List<UserDataBean.ListBean>> userRecordList = new State<>(new ArrayList<>());
    }
}
